#!/usr/bin/python
# -*- coding: utf-8 -*-

def convert(imgFile, labelFile, outFile, imgSetSize):  # 转换数据格式
    f = open(imgFile, "rb")
    o = open(outFile, "w")
    l = open(labelFile, "rb")

    f.read(16)  # 逐个字节或字符读取文件中的内容
    l.read(8)
    images = []
    for i in range(imgSetSize):  # 需要转换的数据对象个数为imgSetSize
        image = [ord((l.read(1)))]  # ord()函数是chr()函数或unichr()函数的配对函数
        # chr()函数: 对于8位的ASCII字符串
        # unichr()函数: 对于Unicode对象

        for j in range(28 * 28):  # 由于每个图片的像素是28*28，按这个尺寸还原每一幅图，但张量（数组）会被转换成1*728的格式
            image.append(ord(f.read(1)))
        images.append(image)

    for image in images:
        o.write(",".join(str(pix) for pix in image) + "\n")

    f.close()
    o.close()
    l.close()


if __name__ == '__main__':
    # 训练集有6w幅图
    convert('train-images-idx3-ubyte', 'train-labels-idx1-ubyte', 'mnist_train.csv', 60000)
    # 验证集有1w幅图
    convert('t10k-images-idx3-ubyte', 't10k-labels-idx1-ubyte', 'mnist_test.csv', 10000)
    print("Task accomplished!")
